package com.china08.yxyapi.schedule.activity.healthcompetition;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.mg.huodong.healthcompetition.YxyCompetitionDistrict;
import com.china08.yxyapi.entity.mg.huodong.healthcompetition.YxyCompetitionSchool;
import com.china08.yxyapi.entity.mg.huodong.healthcompetition.YxyCompetitionStudent;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.huodong.YxyCompetitionDistrictRepository;
import com.china08.yxyapi.repository.mg.huodong.YxyCompetitionSchoolRepository;
import com.china08.yxyapi.util.YxyScheduleRunnableUtil;

/**
 * 
 * 健康知识竞赛 统计页面 定时执行
 * 
 * @author shijiahe
 */
//
@Component
@Configurable
@EnableScheduling
public class HuodongHealthCompetitionScheduledTasks {

    private static Logger LOGGER = LoggerFactory.getLogger(HuodongHealthCompetitionScheduledTasks.class);
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${yx.rest.api.yx.path}")
    private String yxpath;
    @Autowired
    private YxyCompetitionDistrictRepository yxyCompetitionDistrictRepository;
    @Autowired
    private YxyCompetitionSchoolRepository yxyCompetitionSchoolRepository;

    // @Scheduled(cron = " 0 0/15 * * * * ")
    // @Scheduled(fixedRate = 1000 * 60)
    public void userRoleInitTask() {
        System.out.println("" //
                + "=================================================\n"
                + "-------------------------------------------------");

        // ##
        // 负载均衡环境:只在特定服务器上执行
        // ##
        // 检测定时任务是否可执行
        if (!YxyScheduleRunnableUtil.checkRunnable()) { return; }

        List<String> noList = new ArrayList<>();
        noList.add("ff8080815ba9422a015bb326acfa1599");
        noList.add("ff8080815ac67d12015b03a25cf70a5c");
        noList.add("ff8080815a032de4015a3c0fdf2d7a16");
        noList.add("ff808081598c885c01599b2857f52de7");
        noList.add("ff80808148f98a490148fcdab1760008");
        DecimalFormat df = new DecimalFormat("######0.00");
        // 统计分区参与竞赛学生
        Criteria criteria = Criteria.where("status").is(2).and("areaCodeCity").is("230100").and("areaCodeDistrict")
                .ne("").and("schoolId").nin(noList);

        String[] fields = new String[] { "avg", "total", "areaCodeProvince", "areaNameProvince", "areaCodeCity",
                "areaNameCity", "areaCodeDistrict", "areaNameDistrict" };
        TypedAggregation<YxyCompetitionStudent> tongjidistrict = Aggregation.newAggregation(YxyCompetitionStudent.class,
                Aggregation.match(criteria),
                Aggregation.group("areaCodeDistrict").avg("score").as("avg").count().as("total")
                        .first("areaCodeProvince").as("areaCodeProvince").first("areaNameProvince")
                        .as("areaNameProvince").first("areaCodeCity").as("areaCodeCity").first("areaNameCity")
                        .as("areaNameCity").first("areaCodeDistrict").as("areaCodeDistrict").first("areaNameDistrict")
                        .as("areaNameDistrict"),
                Aggregation.project(fields));
        AggregationResults<YxyCompetitionDistrict1> resultZongtotal = mongoTemplate.aggregate(tongjidistrict,
                YxyCompetitionDistrict1.class);
        List<YxyCompetitionDistrict1> dateModelLsttotal = resultZongtotal.getMappedResults();

        if (dateModelLsttotal.size() > 0) { // 格式化平均分
            for (YxyCompetitionDistrict1 entity : dateModelLsttotal) {
                YxyCompetitionDistrict yxy1 = yxyCompetitionDistrictRepository
                        .findTop1ByAreaCodeDistrict(entity.areaCodeDistrict);
                if (yxy1 == null) {
                    yxy1 = new YxyCompetitionDistrict();
                    yxy1.setAreaCodeCity(entity.areaCodeCity);
                    yxy1.setAreaNameCity(entity.areaNameCity);
                    yxy1.setAreaCodeDistrict(entity.areaCodeDistrict);
                    yxy1.setAreaNameDistrict(entity.areaNameDistrict);
                    yxy1.setAreaCodeProvince(entity.areaCodeProvince);
                    yxy1.setAreaNameProvince(entity.areaNameProvince);
                }
                yxy1.setTotal(entity.total);
                yxy1.setAvg(Double.valueOf(df.format(entity.avg)));
                yxyCompetitionDistrictRepository.save(yxy1);
            }
        }

        // 补全分区参与竞赛学生
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
            Map<String, Object> formMap = new HashMap<String, Object>();
            formMap.put("id", "230100");
            HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
            Districts httpResult = restTemplate.postForObject(yxpath + "/comm/area/pid", formEntity, Districts.class);
            List<Area> districts = httpResult.areas;
            for (Area district : districts) {
                YxyCompetitionDistrict yxy = yxyCompetitionDistrictRepository.findTop1ByAreaCodeDistrict(district.id);
                if (yxy == null) {
                    yxy = new YxyCompetitionDistrict();
                    yxy.setAreaCodeProvince("230000");
                    yxy.setAreaNameProvince("黑龙江省");
                    yxy.setAreaCodeCity("230100");
                    yxy.setAreaNameCity("哈尔滨市");
                    yxy.setAreaCodeDistrict(district.id);
                    yxy.setAreaNameDistrict(district.name);
                    yxy.setTotal(0);
                    yxy.setAvg(0d);
                    yxyCompetitionDistrictRepository.save(yxy);
                }
            }
        } catch (Exception e) {
            LOGGER.info("HuodongHealthCompetitionScheduledTasks*********************获取学生学段接口链接失败");
            e.printStackTrace();
        }
        // 统计分学校参与竞赛学生
        TypedAggregation<YxyCompetitionStudent> tongjischool = Aggregation.newAggregation(YxyCompetitionStudent.class,
                Aggregation.match(
                        Criteria.where("status").is(2).and("areaCodeCity").is("230100").and("areaCodeDistrict").ne("")),
                Aggregation.group("schoolId").avg("score").as("avg").count().as("total").first("schoolId")
                        .as("schoolId").first("schoolName").as("schoolName").first("areaCodeProvince")
                        .as("areaCodeProvince").first("areaNameProvince").as("areaNameProvince").first("areaCodeCity")
                        .as("areaCodeCity").first("areaNameCity").as("areaNameCity").first("areaCodeDistrict")
                        .as("areaCodeDistrict").first("areaNameDistrict").as("areaNameDistrict"));
        AggregationResults<YxyCompetitionSchool1> tongjischools = mongoTemplate.aggregate(tongjischool,
                YxyCompetitionSchool1.class);
        List<YxyCompetitionSchool1> tongjischoollist = tongjischools.getMappedResults();
        if (dateModelLsttotal.size() > 0) {
            // 格式化平均分
            for (YxyCompetitionSchool1 entity : tongjischoollist) {
                YxyCompetitionSchool yxy1 = yxyCompetitionSchoolRepository.findTop1BySchoolId(entity.schoolId);
                if (yxy1 == null) {
                    yxy1 = new YxyCompetitionSchool();
                    yxy1.setSchoolId(entity.schoolId);
                    yxy1.setSchoolName(entity.schoolName);
                    yxy1.setAreaCodeCity(entity.areaCodeCity);
                    yxy1.setAreaNameCity(entity.areaNameCity);
                    yxy1.setAreaCodeDistrict(entity.areaCodeDistrict);
                    yxy1.setAreaNameDistrict(entity.areaNameDistrict);
                    yxy1.setAreaCodeProvince(entity.areaCodeProvince);
                    yxy1.setAreaNameProvince(entity.areaNameProvince);
                }
                yxy1.setJoinTotal(entity.total);
                yxy1.setAvg(Double.valueOf(df.format(entity.avg)));
                yxyCompetitionSchoolRepository.save(yxy1);
            }
        }
        // 补全分学校参与竞赛学生
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
            Map<String, Object> formMap = new HashMap<String, Object>();
            formMap.put("citycode", "230100");
            HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
            Schools httpResult = restTemplate.postForObject(yxpath + "/comm/stucount/schlst/studentcount", formEntity,
                    Schools.class);
            List<School> schools = httpResult.schools;
            for (School sch : schools) {
                YxyCompetitionSchool yxyCompetitionSchool = yxyCompetitionSchoolRepository.findTop1BySchoolId(sch.id);
                if (yxyCompetitionSchool == null) {
                    yxyCompetitionSchool = new YxyCompetitionSchool();
                    yxyCompetitionSchool.setAreaCodeProvince("230000");
                    yxyCompetitionSchool.setAreaNameProvince("黑龙江省");
                    yxyCompetitionSchool.setAreaCodeCity("230100");
                    yxyCompetitionSchool.setAreaNameCity("哈尔滨市");
                    yxyCompetitionSchool.setAreaCodeDistrict(sch.districtcode);
                    yxyCompetitionSchool.setAreaNameDistrict(sch.districtname);
                    yxyCompetitionSchool.setAvg(0d);
                    yxyCompetitionSchool.setJoinTotal(0);
                    yxyCompetitionSchool.setRate(0d);
                    yxyCompetitionSchool.setSchoolId(sch.id);
                    yxyCompetitionSchool.setSchoolName(sch.name);
                    yxyCompetitionSchool.setTotal(sch.total);
                } else {
                    Double rate = 0.0d;
                    if (sch.total != 0) {
                        Double aLong = (double) yxyCompetitionSchool.getJoinTotal() / sch.total;
                        rate = Double.valueOf(df.format(aLong * 100));
                    }
                    yxyCompetitionSchool.setRate(rate);
                    yxyCompetitionSchool.setTotal(sch.total);
                }
                yxyCompetitionSchool.setAddress(sch.address);
                yxyCompetitionSchoolRepository.save(yxyCompetitionSchool);
            }
        } catch (Exception e) {
            LOGGER.info("HuodongHealthCompetitionScheduledTasks*********************获取学校接口链接失败");
            e.printStackTrace();
        }
        LOGGER.info("健康知识竞赛统计完成");

    }

    protected static class ReqModel extends YxyApiReqModel {
        public String citycode = "230100";
        public String cityname = "哈尔滨市";
        public String provincecode = "230000";
        public String provincename = "黑龙江省";
    }

    protected static class RespModel extends YxyApiRespModel {
        // 统计是否成功提示
        public String notice;
    }

    protected static class Districts {
        public List<Area> areas;
    }

    protected static class Area {
        public String id;
        public String name;
    }

    protected static class Schools {
        public List<School> schools;
    }

    protected static class School {
        public String id;
        public String name;
        public String address;
        public Integer total;
        public String districtcode;
        public String districtname;
    }

    public class YxyCompetitionDistrict1 {
        public Integer total;
        public Double avg;
        public String areaCodeProvince;
        public String areaNameProvince;
        public String areaCodeCity;
        public String areaNameCity;
        public String areaCodeDistrict;
        public String areaNameDistrict;

    }

    public class YxyCompetitionSchool1 {
        public String schoolId;
        public String schoolName;
        public Integer total;
        public Double avg;
        public String areaCodeProvince;
        public String areaNameProvince;
        public String areaCodeCity;
        public String areaNameCity;
        public String areaCodeDistrict;
        public String areaNameDistrict;

    }
}
